﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;

namespace NetCoreCMS.Web.Areas.Admin.Controllers
{
    public class User_EditController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Users/User_Edit.cshtml";
        string defaultpassword = "0|0|0|0"; //默认显示密码
        protected string action = CMSEnums.ActionEnum.Add.ToString(); //操作类型
        private int id = 0;

        public IUsersService _users { get; set; }
        public IUser_groupsService _user_groups { get; set; }
        public IUser_login_logService _user_login_log{get;set;}
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.Result != null)
                return;
            ChkAdminLevel("user_list", CMSEnums.ActionEnum.View.ToString()); //检查权限
            ViewBag.defaultpassowrd = defaultpassword;
            string _action = Request.Query["action"];
            if (!string.IsNullOrEmpty(_action) && _action == CMSEnums.ActionEnum.Edit.ToString())
            {
                this.action = CMSEnums.ActionEnum.Edit.ToString();//修改类型
                int.TryParse(Request.Query["id"],out this.id);
                if (this.id == 0)
                {
                    JscriptMsg("传输参数不正确！", "back");
                    filterContext.Result = View(EDIT_RESULT_VIEW);
                    return;
                }
                if (!_users.Exists(this.id))
                {
                    JscriptMsg("信息不存在或已被删除！", "back");
                    filterContext.Result = View(EDIT_RESULT_VIEW);
                    return;
                }
            }
            ViewBag.Id = this.id;
            ViewBag.Action = this.action;
        }
        // GET: /admin/User_Edit/

        public ActionResult Index()
        {
            TreeBind("where is_lock=0"); //绑定组别
            if (action == CMSEnums.ActionEnum.Edit.ToString())
            {
                ShowInfo(this.id);
            }
            else
            {
                NetCoreCMS.Models.Users model = new NetCoreCMS.Models.Users();
                model.amount = 0;
                model.point = 0;
                model.exp = 0;
                model.reg_time = DateTime.Now;
                model.reg_ip = CMSRequest.GetClientUserIp(HttpContext);
                model.birthday = new DateTime(1900, 1, 1);
                ViewData["model"] = model;
            }
            return View(WEB_VIEW);
        }

        #region 绑定组别=================================
        private void TreeBind(string strWhere)
        {
            var dt = _user_groups.GetList(strWhere+" order by grade asc,id asc");
            List<SelectListItem> groupListItems = new List<SelectListItem>();
            groupListItems.Add(new SelectListItem() { Text = "请选择组别...", Value = "" });
            foreach (User_groups dr in dt)
            {
                groupListItems.Add(new SelectListItem() { Text = dr.title, Value = dr.id.ToString() });
            }
            ViewData["groupListItems"] = groupListItems;
        }
        #endregion

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            var model = _users.GetModel(_id);
            if (!string.IsNullOrEmpty(model.password))
            {
                model.password = defaultpassword;
            }
            ViewData["model"] = model;
            //查找最近登录信息
            var logModel = _user_login_log.GetLastModel(model.user_name);
            ViewData["logModel"] = logModel;
        }
        #endregion

        #region 增加操作=================================
        private bool DoAdd()
        {
            bool result = false;
            NetCoreCMS.Models.Users model = new NetCoreCMS.Models.Users();
            model.group_id = int.Parse(Request.Form["ddlGroupId"]);
            model.status = int.Parse(Request.Form["rblStatus"]);
            //检测用户名是否重复
            if (_users.Exists(Request.Form["txtUserName"].FirstOrDefault().Trim()))
            {
                return false;
            }
            model.user_name = Request.Form["txtUserName"].FirstOrDefault().Trim();
            //获得6位的salt加密字符串
            model.salt = Utils.GetCheckCode(6);
            //以随机生成的6位字符串做为密钥加密
            model.password = AESEncryptHelper.Encode(Request.Form["txtPassword"].FirstOrDefault().Trim(), model.salt);
            model.email = Request.Form["txtEmail"];
            model.nick_name = Request.Form["txtNickName"];
            model.avatar = Request.Form["txtAvatar"];
            model.sex = Request.Form["rblSex"];
            DateTime _birthday;
            if (DateTime.TryParse(Request.Form["txtBirthday"].FirstOrDefault().Trim(), out _birthday))
            {
                model.birthday = _birthday;
            }
            model.telphone = Request.Form["txtTelphone"].FirstOrDefault().Trim();
            model.mobile = Request.Form["txtMobile"].FirstOrDefault().Trim();
            model.qq = Request.Form["txtQQ"].FirstOrDefault();
            model.msn = Request.Form["txtMsn"].FirstOrDefault();
            model.address = Request.Form["txtAddress"].FirstOrDefault().Trim();
            model.amount = decimal.Parse(Request.Form["txtAmount"].FirstOrDefault().Trim());
            model.point = int.Parse(Request.Form["txtPoint"].FirstOrDefault().Trim());
            model.exp = int.Parse(Request.Form["txtExp"].FirstOrDefault().Trim());
            model.reg_time = DateTime.Now;
            model.reg_ip = CMSRequest.GetClientUserIp(HttpContext);

            if (_users.Add(model) > 0)
            {
                AddAdminLog(CMSEnums.ActionEnum.Add.ToString(), "添加用户:" + model.user_name); //记录日志
                result = true;
            }
            return result;
        }
        #endregion

        #region 修改操作=================================
        private bool DoEdit(int _id)
        {
            bool result = false;
            var model = _users.GetModel(_id);

            model.group_id = int.Parse(Request.Form["ddlGroupId"]);
            model.status = int.Parse(Request.Form["rblStatus"]);
            //判断密码是否更改
            if (Request.Form["txtPassword"].FirstOrDefault().Trim() != defaultpassword)
            {
                //获取用户已生成的salt作为密钥加密
                model.password = AESEncryptHelper.Encode(Request.Form["txtPassword"].FirstOrDefault().Trim(), model.salt);
            }
            model.email = Request.Form["txtEmail"];
            model.nick_name = Request.Form["txtNickName"];
            model.avatar = Request.Form["txtAvatar"];
            model.sex = Request.Form["rblSex"];
            DateTime _birthday;
            if (DateTime.TryParse(Request.Form["txtBirthday"].FirstOrDefault().Trim(), out _birthday))
            {
                model.birthday = _birthday;
            }
            model.telphone = Request.Form["txtTelphone"].FirstOrDefault().Trim();
            model.mobile = Request.Form["txtMobile"].FirstOrDefault().Trim();
            model.qq = Request.Form["txtQQ"];
            model.msn = Request.Form["txtMsn"];
            model.address = Request.Form["txtAddress"].FirstOrDefault().Trim();
            model.amount = Utils.StrToDecimal(Request.Form["txtAmount"].FirstOrDefault().Trim(), 0);
            model.point = Utils.StrToInt(Request.Form["txtPoint"].FirstOrDefault().Trim(), 0);
            model.exp = Utils.StrToInt(Request.Form["txtExp"].FirstOrDefault().Trim(), 0);

            if (_users.Update(model))
            {
                AddAdminLog(CMSEnums.ActionEnum.Edit.ToString(), "修改用户信息:" + model.user_name); //记录日志
                result = true;
            }
            return result;
        }
        #endregion

        //保存
        [HttpPost]
        public ActionResult SubmitSave()
        {
            if (action == CMSEnums.ActionEnum.Edit.ToString()) //修改
            {
                ChkAdminLevel("user_list", CMSEnums.ActionEnum.Edit.ToString()); //检查权限
                if (!DoEdit(this.id))
                {
                    JscriptMsg("保存过程中发生错误！", "");
                }
                else
                {
                    JscriptMsg("修改会员成功！", "../user_list/index");
                }
            }
            else //添加
            {
                ChkAdminLevel("user_list", CMSEnums.ActionEnum.Add.ToString()); //检查权限
                if (!DoAdd())
                {
                    JscriptMsg("保存过程中发生错误！", "");
                }
                else
                {
                    JscriptMsg("添加会员成功！", "../user_list/index");
                }
            }
            return View(EDIT_RESULT_VIEW);
        }
    }
}
